package com.hoongs.v1.server;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hoongs.v1.entity.SocketMsg;
import com.hoongs.v1.entity.SocketMsgRecord;
import com.hoongs.v1.entity.User;
import com.hoongs.v1.mapper.SocketMsgMapper;
import com.hoongs.v1.mapper.SocketMsgRecordMapper;
import com.hoongs.v1.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@ServerEndpoint(value = "/ws/{userId}")  // 接口路径 ws://localhost:8087/ws/userId;
public class WebSocketServer {

    /**
     * 用来解决webSocket中无法注入mapper
     */

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    //虽然@Component默认是单例模式的，但springboot还是会为每个websocket连接初始化一个bean，所以可以用一个静态set保存起来。
    private static CopyOnWriteArraySet<WebSocketServer> webSockets = new CopyOnWriteArraySet<>();
    // 用来存在线连接数
    private static Map<String, Session> sessionPool = new HashMap<String, Session>();

    private static UserMapper userMapper;
    private static SocketMsgMapper socketMsgMapper;
    private static SocketMsgRecordMapper socketMsgRecordMapper;


    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        WebSocketServer.userMapper = userMapper;
    }

    @Autowired
    public void setSocketMapper(SocketMsgMapper socketMsgMapper) {
        WebSocketServer.socketMsgMapper = socketMsgMapper;
    }

    @Autowired
    public void setSocketMsgRecordMapper(SocketMsgRecordMapper socketMsgRecordMapper) {
        WebSocketServer.socketMsgRecordMapper = socketMsgRecordMapper;
    }

    /**
     * 链接成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        try {
            this.session = session;
            webSockets.add(this);
            sessionPool.put(userId, session);
            log.info("【websocket消息】有新的连接，总数为:" + webSockets.size());

            QueryWrapper<SocketMsgRecord> wrapper = new QueryWrapper<>();
            wrapper.eq("to_id", userId);
            wrapper.eq("is_read", "0");
            List<SocketMsgRecord> msgs = socketMsgRecordMapper.selectList(wrapper);
            for (SocketMsgRecord msg : msgs) {
                if (StringUtils.isNotBlank(msg.getToId())) {
                    sendMsgToUser(msg);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 链接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        try {
            webSockets.remove(this);
            log.info("【websocket消息】连接断开，总数为:" + webSockets.size());
        } catch (Exception e) {
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(Session session, String message) {
        log.info("【websocket消息】收到客户端消息:" + message);
        JSONObject receive = JSON.parseObject(message);
        String msgId = receive.getString("msgId");
        String acType = receive.getString("actionType");
        SocketMsgRecord socketMsg = socketMsgRecordMapper.selectById(msgId);
        switch (acType) {
//            // 设置已读
//            case "100":
//                socketMsg.setIsRead("1");
//                socketMsgRecordMapper.updateById(socketMsg);
//                break;
//            // 设置未读
//            case "101":
//                socketMsg.setIsRead("0");
//                socketMsgRecordMapper.updateById(socketMsg);
//                break;
        }
    }

    /**
     * 发送错误时的处理
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {

        log.error("用户错误:" + session + ",原因:" + error.getMessage());
        error.printStackTrace();
    }


    // 此为广播消息
    public void sendAllMessage(String message) {
        log.info("【websocket消息】广播消息:" + message);
        for (WebSocketServer webSocketServer : webSockets) {
            try {
                if (webSocketServer.session.isOpen()) {
                    webSocketServer.session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息（根据消息记录发送消息给用户）
    public void sendMsgToUser(SocketMsgRecord socketMsg) {
        Session session = sessionPool.get(socketMsg.getToId());
        if (session != null && session.isOpen()) {
            try {
                log.info("【websocket消息】 单点消息:" + socketMsg.getContent());
                synchronized (session) {
                    session.getBasicRemote().sendText(JSON.toJSONString(socketMsg));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息（新增消息发送给用户）
    public void sendMsgToUser(SocketMsg socketMsg) {
        Session session = sessionPool.get(socketMsg.getToId());
        if (StringUtils.isBlank(socketMsg.getId())) {
            socketMsgMapper.insert(socketMsg);
            socketMsgRecordMapper.insert(SocketMsgRecord.fromMsg(socketMsg));
        }
        if (session != null && session.isOpen()) {
            try {
                log.info("【websocket消息】 单点消息:" + socketMsg.getContent());
                synchronized (session) {
                    session.getBasicRemote().sendText(JSON.toJSONString(socketMsg));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息
    public void sendMsgByRole(String role, SocketMsg socketMsg) {
        if (StringUtils.isBlank(role)) return;

        QueryWrapper<User> wrapper = new QueryWrapper();
        wrapper.eq("role", role);
        wrapper.eq("status", "1");

        List<User> userList = userMapper.selectList(wrapper);
        for (User user : userList) {
            socketMsg.setToId(user.getId());
            socketMsg.setToName(user.getUsername());
            sendMsgToUser(socketMsg);
        }
    }

    // 此为单点消息(多人)
    public void sendMoreMessage(String[] userIds, String message) {
        for (String userId : userIds) {
            Session session = sessionPool.get(userId);
            if (session != null && session.isOpen()) {
                try {
                    log.info("【websocket消息】 单点消息:" + message);
                    session.getAsyncRemote().sendText(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
